import React from 'react';
import {WeaTools,WeaBrowser,WeaDatePicker,WeaFormItem,WeaSelect,WeaTimeRangePicker,WeaDropdown,WeaInput,WeaLocaleProvider} from 'ecCom';
import {Menu,Button,message,Spin} from 'antd';
import {inject, observer,} from 'mobx-react';
import {observable,action,toJS} from 'mobx';
import moment from 'moment';
import './style';
const getLabel = WeaLocaleProvider.getLabel;

@observer
class View extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          loading: false,
          spinning: false,
          value: moment(),
          valuestr: moment().format('YYYY-MM-DD'),
          timestr: ['13:00','14:00'],
          selectlistVisible: false,
          selectStr: getLabel(1340,'所有人'),
          selectId: '0', //0:所有人；1：本人；2：所有上级；3：直接下级；4：所有下级；5：关注者
          attentionData: [],
          inputValue: '',
          hrmId: '',
          eid: this.props.params.eid, // 门户元素id传参数
          displayWorkplanDatas: [],
          hrmReplaceDatas: [],
        };
    }

    componentWillMount() {
     
    }

    componentDidMount() {
      const {valuestr,selectId} = this.state;
      setTimeout(() => { // 解决设置面只能异步保存问题，门户还在优化中
        this.getDisplayWorkplan(valuestr, selectId, '',);
      }, 1000);
    }

    onclickSelectList = (param, key) => {
      const {valuestr} = this.state;
      let str = param;
      if(typeof(param) !== 'string') {
        str = param[0];
      }
      this.refs.browserInput.set([{id: ' ', name: ' '}]);
      this.setState({selectStr: str,selectId: key, hrmReplaceDatas: []});
      this.getDisplayWorkplan(valuestr, key, '',);
    }

    setTime = (time) => {
      let timestr = '';
      const {selectId,hrmId} = this.state;
      if(time instanceof Date) {
        timestr = this.changeDateFormat(time);
      }else{
        timestr = time.format('YYYY-MM-DD');
      }
      this.setState({value: time, valuestr: timestr});
      this.getDisplayWorkplan(timestr, selectId, hrmId);
    }

    changeDateFormat = data => {
      if (typeof (data) === 'string' && data != '') {
        return data
      }
      //日期格式转为yyyy-MM-dd
      let now = data || new Date();
      let year = now.getFullYear();
      let month = (now.getMonth() + 1).toString();
      let day = (now.getDate()).toString();
      if (month.length == 1) {
        month = "0" + month;
      }
      if (day.length == 1) {
        day = "0" + day;
      }
      let dateString = year + "-" + month + "-" + day;
      return dateString;
    }

    getAttentionData = (param, callback) => { // 获取关注者
      let params = {...param,noLimit: 1};
      WeaTools.callApi('/api/workplan/calendar/getAttentionData', 'POST', params).then(res => {
        this.setState({attentionData: res.data})
        typeof(callback) == 'function' && callback();
      });
    }

    addAttentionBrowser = (ids) => { // 添加关注者
      let params = {touserid: ids};
      const {valuestr} = this.state;
      WeaTools.callApi('/api/workplan/calendar/updateAttention', 'POST', params).then(res => {
        if(res.api_status) {
          message.success(getLabel(22619,'保存成功') );
          this.getDisplayWorkplan(valuestr, 5, '',);
        }else{
          message.error(getLabel(22620,'保存失败') );
        }
      });
    }

    submit = (callback) => { // 保存-添加
      const {valuestr,timestr,inputValue} = this.state;
      let params = {
        planName: inputValue,
        beginDate: valuestr,
        endDate: valuestr,
        beginTime: timestr[0],
        endTime: timestr[1],
      };
      if(inputValue==='') {
        message.error(getLabel(505887,'必填未填写！') );
      }else{
        this.setState({loading: true});
        WeaTools.callApi('/api/workplan/base/add', 'POST', params).then(res => {
          if(res.api_status) {
            message.success(getLabel(22619,'保存成功') );
            this.setState({loading: false, inputValue: ''});
            typeof(callback) == 'function' && callback();
          }else{
            message.error(getLabel(22620,'保存失败'));
            this.setState({loading: false});
          }
        });
      }
    }

    getDisplayWorkplan = (selectDate, objType, hrmId) => {
      // selectDate,objType, hrmId  选中日期 查询类型 查询指定人员
      const {eid} = this.state;
      let params = {
        selectDate: selectDate,
        objType: objType,
        hrmId: hrmId,
        viewType: 1,
      };
      params = {...params, eid: eid}; // 门户元素id传参数
      this.setState({spinning: true});
      WeaTools.callApi('/api/portal/element/hdpanel/getListData', 'POST', params).then(res => {
        this.setState({spinning: false, displayWorkplanDatas: res.datas});
      });
    }

    render() {
        const {loading,spinning,value,valuestr,timestr,selectlistVisible,selectStr,displayWorkplanDatas,inputValue,attentionData,hrmReplaceDatas} = this.state;
        return (
          <div className="portal-element-staffkanban" onClick={(e) => {}}>
            <div className='portal-element-staffkanban-topbar'>
              <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@zaon5z`}
                ref='browserInput'
                className={'browser-staff'}
                type={1}
                placeholder={getLabel(26919,'请输入姓名')}
                textDecoration={true}
                inputStyle={{ width: 200, height: 28, overflow: 'auto' }}
                replaceDatas={hrmReplaceDatas}
                onChange={(ids, names, datas) =>{
                  this.setState({hrmId: ids, hrmReplaceDatas: datas});
                  this.getDisplayWorkplan(valuestr, '', ids,)
                }}
              />
              <div className='selectHrms'>
                {/* 0:所有人；1：本人；2：所有上级；3：直接下级；4：所有下级；5：关注者*/}
                <WeaDropdown ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@yy6tjl`} overlay={
                  <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@fiuuzc`} onClick={( item, key, selectedKeys ) => {this.onclickSelectList(item.item.props.children, item.key)}}>
                    <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@1730p8`} key="0">{getLabel(1340,'所有人')}</Menu.Item> 
                    <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@hnajg3`} key="1">{getLabel(15763,'本人') }</Menu.Item>
                    <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@6m1atc`} key="2">{getLabel(15762,'所有上级') }</Menu.Item>
                    <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@0vs8bq`} key="3">{getLabel(15764,'直接下级') }</Menu.Item>
                    <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@rqmnib`} key="5">{getLabel(25472,'关注者') }
                      <span className='icon-coms-Need-feedback' style={{marginLeft: '10px'}} onClick={()=>{this.getAttentionData('',()=>this.refs.attentionRef.openModal())}}></span>
                    </Menu.Item>
                  </Menu>}
                >
                  {selectStr}
                </WeaDropdown>
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@qom5uw`}
                  ref='attentionRef'
                  title={getLabel(83496,"多人力资源")}
                  type={17}
                  textDecoration={true}
                  customized
                  memorise // 添加默认值
                  onChange={(ids, names, datas)=> this.addAttentionBrowser(ids)}
                  isSingle={false}
                  replaceDatas={attentionData}
                />
              </div>
              <div className='datepicker'>
                <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@28emfb`}
                  arrow
                  type="day"
                  date={value}
                  onChange={value => {this.setTime(value)}}
                />
              </div>
              <div className='addcondition'>
                <div className='span' onClick={() => {this.setState({selectlistVisible: !selectlistVisible}); return false;}}><span>+</span><span>{getLabel(384113,'添加')}</span></div>
                <div className='addFormlist' style={{display: selectlistVisible ? 'block' : 'none'}} >
                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@gzoi9p`} 
                      label={getLabel(19736,'时间') }
                      labelCol={{span: 3}}
                      wrapperCol={{span: 21}}
                    >
                      <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@i243a6`}
                        noInput
                        value={valuestr}
                        onChange={value => {this.setState({valuestr: value })}}
                      />
                      <div className='date-range' style={{ display: 'inline-block' }}>
                      <WeaTimeRangePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaTimeRangePicker@tbo3bz`}
                        value={timestr}
                        onChange={v=>this.setState({timestr:v})}
                      />
                      </div>
                    </WeaFormItem>
                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@7unmnb`} 
                      label={getLabel(33368,'内容')}
                      labelCol={{span: 3}}
                      wrapperCol={{span: 20}}
                    >
                      <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@wgpt5b`} 
                        id="inputContent"
                        viewAttr={3}
                        value={inputValue}
                        onChange={(data) => {this.setState({inputValue: data})}}
                      />
                    </WeaFormItem>
                    <div className='addButton'>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m4cwbh`} type='primary' disabled={loading} loading={loading} onClick={()=>this.submit(()=>this.setState({selectlistVisible: false}))}>{getLabel(30986,'保存') }</Button>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@90v0wm`} onClick={() => {this.setState({selectlistVisible: false})}}>{getLabel(31129,'取消')}</Button>
                    </div>
                  </div>
              </div>
            </div>
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@wyirtc`} spinning={spinning}>
              <div className='portal-element-staffkanban-container'>
                {
                  displayWorkplanDatas && displayWorkplanDatas.length>0 ? 
                    displayWorkplanDatas.map(res => {
                      return (
                        <div className='list' dangerouslySetInnerHTML={{__html: res}}></div>
                      )
                    })
                  :
                  <div className='no-data'>
                    <span>
                      <i className='anticon anticon-frown'/>
                      {getLabel(505890,'暂无安排')}
                    </span>
                  </div>
                }
              </div>
            </Spin>
          </div>
        );
    }
}

export default View;
